import { Dialog } from 'vant';
import { VERSION } from "../config/index"

Dialog.setDefaultOptions({
    confirmButtonColor: "#006BE0",
    closeOnPopstate: false
})
//检测新版本升级
export function upgradeForAndroid() {
    //从window中获取Cordova对象
    var cordova = window.cordova
    //apk所在的服务器路径（下载路径）
    /* var url = process.env.VUE_APP_APK_URL + process.env.VUE_APP_APK_NAME + ".apk"; */
    var url = 'http://10.156.8.229/MarsMRE.apk'
    var targetPath = cordova.file.externalCacheDirectory + "Download/Pass/" + "test.apk"; //要下载的目标路径及文件名（本地存储路径）
    var trustHosts = true;
    /* var options = {}; */
    console.log("url:" + url);
    console.log("targetPah:" + targetPath);
    console.log("trustHost:" + trustHosts);
    downLoadApp();
    function downLoadApp() {
        // 初始化FileTransfer对象
        // eslint-disable-next-line no-undef
        var fileTransfer = new FileTransfer();
        fileTransfer.onprogress = function (progressEvent) {
            if (progressEvent.lengthComputable) {
                var downloadProgress = (progressEvent.loaded / progressEvent.total) * 100;
                var result = "已下载：" + Math.floor(downloadProgress) + "%";
                console.log(result, "已经下载")

                if (Math.floor(downloadProgress) == 100) {
                    Dialog.alert({
                        title: result,
                        message: "下载完成后会自动弹出安装",
                        showConfirmButton: false,
                        showCancelButton: true
                    }).then(
                    ).catch(() => {
                        // on cancel
                        navigator.app.exitApp();
                    })
                } else {
                    Dialog.alert({
                        title: result,
                        message: "下载完成后会自动弹出安装",
                        showConfirmButton: false,
                        showCancelButton: false
                    })
                }
            }
        };
        // 调用download方法
        fileTransfer.download(
            url, //uri网络下载路径
            targetPath, //url本地存储路径
            function (entry) {
                console.log("download complete: " + entry.toURL());
                cordova.plugins.fileOpener2.open(
                    targetPath,
                    'application/vnd.android.package-archive',
                    {
                        error: function (e) {
                            console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
                            Dialog.alert({
                                title: "打开下载文件失败",
                                message: "请退出后重新进入应用",
                            }).then(res => {
                                console.log(res);
                                navigator.app.exitApp();
                            })
                        },
                        success: function () {
                            console.log('open successfully');
                        }
                    })
            },
            function (error) {
                // AlertModule.show({ title: "下载失败" })
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("upload error code" + error.code);
            }
        );
    }
}
/*
 * 检测升级方法
 */
export function checkUpgrade(locationVersion) {
    /**
    * 从服务器获取应用的版本信息，和本地应用版本对比
    */
    var serverVersion = VERSION;
    //获取本地App版本;
    console.log("本地版本：" + locationVersion);
    console.log("服务器版本：" + serverVersion);
    /*         var locationVersionNum = parseInt(locationVersion.replace(/\./g, ""))
            var serverVersionNum = parseInt(serverVersion.replace(/\./g, "")) */
    /* if (locationVersionNum < serverVersionNum) {  */
    Dialog.confirm({
        title: '服务器版本：' + serverVersion + '本地版本' + locationVersion + ',请进行升级',
        message: '建议您在WIFI环境下升级',
    }).then(() => {
        // on confirm
        upgradeForAndroid()
    }).catch(() => {
        // on cancel
        navigator.app.exitApp();
    });
    /* } */
    // 监听网络状况，无网络时
    document.addEventListener('offline', function () {
        console.log("网络异常，不能连接到服务器！");
        Dialog.alert({
            title: "网络异常，不能连接到服务器！",
            message: "请在连接网络的情况下升级应用"
        }).then(() => {
            navigator.app.exitApp();
        })
    }, false);
}
